package com.rao.crm.utils;

import com.rao.crm.domain.Customer;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Srao
 * @version 1.0
 * @className UploadUtils
 * @date 2019/9/20 12:29
 * @package com.rao.crm.utils
 * @description
 */
public class UploadUtils {

    /*获得一个随机的文件名*/
    public static String getUuidFileName(String fileName){
        //获得文件的后缀名
        int i = fileName.lastIndexOf(".");//aa.txt
        String substring = fileName.substring(i);//.txt
        return UUID.randomUUID().toString().replace("-", "") + substring;
        //f45af6a840214c27a55817f0e66a819c.txt
    }

    /*创建多级目录*/
    public static String getFilePath(String uuidFileName){
        int code1 = uuidFileName.hashCode();//得到一个32位的数
        int dir1 = code1 & 0xf;//与上00000000000000000000000000001111，作为一级目录
        int code2 = code1 >>> 4;//右移4位，得到一个28位的数
        int dir2 = code2 & 0xf;//与上00000000000000000000000000001111，作为二级目录
        return "/" + dir1 + "/" + dir2;
    }

    /*保存文件*/
    public static String saveFile(String uploadFileName, File upload) throws IOException {
        /*设置根目录*/
        String rootPath = "D:\\upload";
        /*获得随机的文件名*/
        String uuidFileName = UploadUtils.getUuidFileName(uploadFileName);
        /*获得随机的目录*/
        String filePath = UploadUtils.getFilePath(uuidFileName);
        /*创建目录*/
        String path = rootPath + filePath;
        File dir = new File(path);
        if (!dir.exists()){
            dir.mkdirs();
        }
        /*保存文件到刚才创建的目录里面*/
        File file = new File(path + "/" + uuidFileName);
        FileUtils.copyFile(upload, file);

        /*返回图片的路径*/
        return path + "/" + uuidFileName;
    }

    /*删除文件*/
    public static void deleteFile(String cust_image) {
        if (null != cust_image && !"".equals(cust_image)) {
            File file = new File(cust_image);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID().toString());//515d9276-62f0-41d4-b62e-df9888aed15f
        System.out.println("abcdefg".lastIndexOf("b"));//1
        System.out.println("abcdefg".substring(1));//bcdefg
        System.out.println(getUuidFileName("abcdefg.txt"));//f45af6a840214c27a55817f0e66a819c.txt
        System.out.println(getFilePath("f45af6a840214c27a55817f0e66a819c.txt"));

    }
}

